'use client';

import React, { useState, useEffect } from 'react';
import { 
  Search, 
  Download, 
  Clock, 
  Activity, 
  FileText, 
  Tool,
  RefreshCw,
  AlertCircle
} from 'lucide-react';
import { ExecutionTrace, ExecutionStep } from '@/types';
import { 
  formatTimestamp, 
  calculateStepDuration, 
  sortStepsByTime, 
  extractKeyInfo, 
  searchSteps 
} from '@/utils/formatTrace';
import StepCard from './StepCard';

interface TraceViewerProps {
  chatflowId: string;
  sessionId: string;
  onRefresh?: () => void;
}

export default function TraceViewer({ 
  chatflowId, 
  sessionId, 
  onRefresh 
}: TraceViewerProps) {
  const [trace, setTrace] = useState<ExecutionTrace | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [expandedSteps, setExpandedSteps] = useState<Set<number>>(new Set());
  const [viewMode, setViewMode] = useState<'timeline' | 'flow'>('timeline');

  useEffect(() => {
    loadTrace();
  }, [chatflowId, sessionId]);

  const loadTrace = async () => {
    try {
      setLoading(true);
      setError(null);
      const traceData = await fetch(`/api/trace?chatflowId=${chatflowId}&sessionId=${sessionId}`)
        .then(res => res.json());
      
      // 处理数据
      const processedSteps = calculateStepDuration(sortStepsByTime(traceData.steps || []));
      setTrace({
        ...traceData,
        steps: processedSteps
      });
      
      // 默认展开第一步
      if (processedSteps.length > 0) {
        setExpandedSteps(new Set([0]));
      }
    } catch (err) {
      setError('加载执行追踪失败');
      console.error('加载 trace 失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const toggleStep = (index: number) => {
    const newExpanded = new Set(expandedSteps);
    if (newExpanded.has(index)) {
      newExpanded.delete(index);
    } else {
      newExpanded.add(index);
    }
    setExpandedSteps(newExpanded);
  };

  const expandAll = () => {
    if (trace) {
      setExpandedSteps(new Set(trace.steps.map((_, index) => index)));
    }
  };

  const collapseAll = () => {
    setExpandedSteps(new Set());
  };

  const exportTrace = () => {
    if (!trace) return;
    
    const dataStr = JSON.stringify(trace, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `trace-${sessionId}-${Date.now()}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="flex items-center space-x-2">
          <RefreshCw className="w-5 h-5 animate-spin text-primary-600" />
          <span className="text-gray-600">加载执行追踪中...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <p className="text-red-600 mb-4">{error}</p>
          <button
            onClick={loadTrace}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  if (!trace) {
    return (
      <div className="text-center py-8 text-gray-500">
        没有找到执行追踪数据
      </div>
    );
  }

  const keyInfo = extractKeyInfo(trace);
  const filteredSteps = searchSteps(trace.steps, searchQuery);

  return (
    <div className="space-y-6">
      {/* 头部信息 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <h1 className="text-2xl font-bold text-gray-900">执行追踪</h1>
          <div className="flex items-center space-x-2">
            <button
              onClick={loadTrace}
              className="p-2 text-gray-500 hover:text-gray-700 transition-colors"
              title="刷新"
            >
              <RefreshCw className="w-5 h-5" />
            </button>
            <button
              onClick={exportTrace}
              className="flex items-center space-x-2 px-3 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
            >
              <Download className="w-4 h-4" />
              <span>导出</span>
            </button>
          </div>
        </div>

        {/* 统计信息 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
          <div className="bg-blue-50 rounded-lg p-3">
            <div className="flex items-center space-x-2">
              <Activity className="w-5 h-5 text-blue-600" />
              <div>
                <p className="text-sm text-blue-600">执行步骤</p>
                <p className="text-lg font-semibold text-blue-800">{keyInfo.totalSteps}</p>
              </div>
            </div>
          </div>
          
          <div className="bg-yellow-50 rounded-lg p-3">
            <div className="flex items-center space-x-2">
              <Tool className="w-5 h-5 text-yellow-600" />
              <div>
                <p className="text-sm text-yellow-600">工具调用</p>
                <p className="text-lg font-semibold text-yellow-800">{keyInfo.totalTools}</p>
              </div>
            </div>
          </div>
          
          <div className="bg-green-50 rounded-lg p-3">
            <div className="flex items-center space-x-2">
              <FileText className="w-5 h-5 text-green-600" />
              <div>
                <p className="text-sm text-green-600">源文档</p>
                <p className="text-lg font-semibold text-green-800">{keyInfo.totalDocuments}</p>
              </div>
            </div>
          </div>
          
          <div className="bg-purple-50 rounded-lg p-3">
            <div className="flex items-center space-x-2">
              <Clock className="w-5 h-5 text-purple-600" />
              <div>
                <p className="text-sm text-purple-600">总耗时</p>
                <p className="text-lg font-semibold text-purple-800">
                  {keyInfo.totalDuration > 0 ? `${Math.round(keyInfo.totalDuration / 1000)}s` : '-'}
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* 会话信息 */}
        <div className="text-sm text-gray-600 space-y-1">
          <p><span className="font-medium">会话 ID:</span> {sessionId}</p>
          <p><span className="font-medium">流程 ID:</span> {chatflowId}</p>
          {keyInfo.startTime && (
            <p><span className="font-medium">开始时间:</span> {formatTimestamp(keyInfo.startTime)}</p>
          )}
          {keyInfo.endTime && (
            <p><span className="font-medium">结束时间:</span> {formatTimestamp(keyInfo.endTime)}</p>
          )}
        </div>
      </div>

      {/* 控制栏 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-3 sm:space-y-0">
          {/* 搜索 */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <input
              type="text"
              placeholder="搜索步骤内容..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent w-full sm:w-64"
            />
          </div>

          {/* 控制按钮 */}
          <div className="flex items-center space-x-2">
            <button
              onClick={expandAll}
              className="px-3 py-2 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
            >
              展开全部
            </button>
            <button
              onClick={collapseAll}
              className="px-3 py-2 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
            >
              折叠全部
            </button>
          </div>
        </div>
      </div>

      {/* 执行步骤 */}
      <div className="space-y-4">
        {filteredSteps.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            {searchQuery ? '没有找到匹配的步骤' : '没有执行步骤'}
          </div>
        ) : (
          filteredSteps.map((step, index) => (
            <StepCard
              key={`${step.timestamp}-${index}`}
              step={step}
              index={index}
              isExpanded={expandedSteps.has(index)}
              onToggle={() => toggleStep(index)}
            />
          ))
        )}
      </div>

      {/* 聊天消息 */}
      {trace.chatMessages && trace.chatMessages.length > 0 && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">对话记录</h2>
          <div className="space-y-3">
            {trace.chatMessages.map((message, index) => (
              <div
                key={index}
                className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                <div
                  className={`max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${
                    message.role === 'user'
                      ? 'bg-primary-600 text-white'
                      : 'bg-gray-100 text-gray-800'
                  }`}
                >
                  <p className="text-sm whitespace-pre-wrap">{message.content}</p>
                  {message.timestamp && (
                    <p className="text-xs opacity-70 mt-1">
                      {formatTimestamp(message.timestamp)}
                    </p>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
